package com.hongxun.design.activitys;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.bean.Exploration;
import com.hongxun.design.bean.photopassbean.SystemTypeBean;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.interfaces.UpdateMap;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.listeners.LocationNowListenner;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.object_properties.MyMessage;
import com.hongxun.design.ui.MBaiduMap;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.imageutil.UriUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zerdoor_pc on 2016/7/8.
 * 点位导航
 */
public class NavigationActivity extends BaseActivity implements HeadSecond, UpdateMap {
    String projectName = "";
    String number = "", explor_id = "",msgstring="";
    private Handler pointHandler;
    TextView words,bottom_title;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation);
        findBar();
        findView();
        initialization();
    }

    @SuppressLint("NewApi")
    @Override
    public void findBar() {
        Bundle bundle = getIntent().getExtras();
        try {
            number = bundle.getString(MString.number, "");
            msgstring = bundle.getString(MString.CODE, "");
            explor_id = bundle.getString(MString.TYPE, "");
        } catch (Exception e) {
        }
        projectName = MyApp.currProject.getProject_name();
        HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.navigation_layout);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean("", View.INVISIBLE, R.color.login_yellow, ListenerSet.back, projectName, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
    }

    @Override
    protected void onResume() {
        baidumapstyle.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        baidumapstyle.onPause();
        super.onPause();
    }

    @Override
    protected void findView() {
        super.findView();
        findViewAndInit_MapButton();
        bottom_title = (TextView) findViewById(R.id.navigation_bottom_title);
        words = (TextView) findViewById(R.id.navigation_bottom_words1);
        words.setMovementMethod(ScrollingMovementMethod.getInstance());
        bottom_title.setText(number);
        words.setText("直线距离:0米");
    }

    @Override
    protected void initialization() {
        super.initialization();
    }


    /****************************************地图设置******************************************************************/

    /**
     * 设置地图*
     */
    public MapView mMapView;
    public BaiduMap mBaiduMap;
    public MBaiduMap baidumapstyle;
    public static LatLng currentPt;//选定的点位
    LocationNowListenner myListener;//定位

    BDLocation location;
    boolean buldeflag = true;
    public static String projectType = "";

    private void findViewAndInit_MapButton() {
        /**新建与拆旧**/
        baidumapstyle = (MBaiduMap) findViewById(R.id.baidumapstyle);
        mMapView = baidumapstyle.getMapView();
        mBaiduMap = baidumapstyle.getBaiduMap();
        baidumapstyle.setPositionClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //重新定位
                inItLocation();//重新定位
            }
        });

        inItLocation();//重新定位
        setPointMapStatus();
       // isnewlyBuild(newlybuild);
        addPointHandler();
        pointHandler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED,msgstring));
    }

    /**
     * 开启定位图层*
     */
    private void inItLocation() {
        //
        mBaiduMap.setMyLocationEnabled(true);
        myListener = LocationNowListenner.getint(mMapView, this);
        myListener.setIsFirstLoc(true);
        myListener.setIsLocal(true);

    }

    /**
     * 显示与隐藏按钮*
     */
    public void disPlay(View view) {
        LinearLayout setpoint_inf_item = (LinearLayout) findViewById(R.id.navigation_inf_item);
        if (setpoint_inf_item.getVisibility() == View.VISIBLE) {
            setpoint_inf_item.setVisibility(View.GONE);
            ((SimpleDraweeView) view).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.fold));
        } else {
            setpoint_inf_item.setVisibility(View.VISIBLE);
            ((SimpleDraweeView) view).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.unfold));
        }
    }


    /**
     * 新建与拆旧*
     */

    public void isnewlyBuild(View v) {
        if (buldeflag) {
            //新建
            buldeflag = false;
            ((SimpleDraweeView) v).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.newcheck));
            projectType = "11";
        } else {
            //拆旧
            buldeflag = true;
            ((SimpleDraweeView) v).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.oldcheck));
            projectType = "12";
        }
        getExplorationList();
    }


    @Override
    public void updateMapState(LatLng currentPt) {
        NavigationActivity.currentPt = currentPt;
        if (myListener != null) {
            MyApp.bdLocation = myListener.getBDLocation();
            location = myListener.getBDLocation();
        } else {
            location = MyApp.bdLocation;
        }
        addPoint();//加载点位
        try {
            baidumapstyle.addMarka((NavigationActivity) mActivity,Mexploration, mpoint,currentPt,map.get(Mexploration.pt_id),words,bottom_title,true);
        }catch (Exception e){

        }

    }


    boolean flag=true;
    Overlay oo;
    Map<String, SystemTypeBean> map;
    public void addPoint() {
        mBaiduMap.clear();
        baidumapstyle.setMarka(currentPt);
       // setPointMapStatus();

        if (pointData == null || pointData.size() == 0) return;
        try {

                     map = DataUtil.getMapSysData(0);
                     for (Exploration exploration : pointData) {
                        if (!(exploration.lat == null || exploration.lng == null)&&!(exploration.lat.equalsIgnoreCase(MString.erroralt) ||exploration.lng.equalsIgnoreCase(MString.erroralt))) {
                            LatLng point = new LatLng(Double.parseDouble(exploration.lat), Double.parseDouble(exploration.lng));
                            baidumapstyle.addMarka((NavigationActivity) mActivity,exploration, point,currentPt,map.get(exploration.pt_id),words,bottom_title,flag);
                            if (flag){
                                flag=false;
                                mpoint=point;
                                Mexploration=exploration;
                            }
                            if (exploration.before_lat != null && exploration.before_lng != null) {
                                LatLng p1 = new LatLng(Double.parseDouble(exploration.lat), Double.parseDouble(exploration.lng));
                                LatLng p2 = new LatLng(Double.parseDouble(exploration.before_lat), Double.parseDouble(exploration.before_lng));
                                List<LatLng> points = new ArrayList<LatLng>();
                                points.add(p1);
                                points.add(p2);
                                OverlayOptions ooPolyline = new PolylineOptions().width(10)
                                        .color(R.color.red).points(points);
                                  mBaiduMap.addOverlay(ooPolyline);
                            }
                        }
                    }

                    if (mpoint!=null&&currentPt!=null &&!(currentPt.longitude<0||currentPt.latitude<0||currentPt.longitude==4.9E-324||currentPt.latitude==4.9E-324)){
                        List<LatLng> points = new ArrayList<LatLng>();
                        points.add(mpoint);
                        points.add(currentPt);
                        OverlayOptions ooPolyline = new PolylineOptions().width(10)
                                .color(R.color.red).points(points);
                        oo=mBaiduMap.addOverlay(ooPolyline);
                    }
                    //pointHandler.sendEmptyMessage(2);

        } catch (Exception e) {
        }
    }
    private  LatLng mpoint;
    public void updateWords(String s ,int num){
        pointHandler.sendMessage(MyMessage.getMessage(2, num, 0, s));

    }
    Exploration Mexploration;
    public void updateLine(LatLng point,Exploration exploration1){
        if (oo==null){
            mpoint=point;
            Mexploration= exploration1;
            pointHandler.sendEmptyMessage(1);
        }else{
            mpoint=point;
            Mexploration= exploration1;
            oo.remove();
            List<LatLng> points = new ArrayList<LatLng>();
            points.add(mpoint);
            points.add(currentPt);
            OverlayOptions ooPolyline = new PolylineOptions().width(10)
                    .color(R.color.red).points(points);
            oo=mBaiduMap.addOverlay(ooPolyline);
        }

    }

    private void setPointMapStatus() {
        if (currentPt == null) return;
        baidumapstyle.setMarka(currentPt);

        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().target(currentPt).zoom(MyApp.zoom).build()));
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(currentPt));//将位置设为中心点
    }
    /*************************************点位请求***************************************************/
    /**
     * 获取点位列表*
     */
    private void getExplorationList() {

        MyApp.HTTP.getExplorationList(pointHandler, HttpStringUtil.SUCCESSED, projectType, MyApp.currProject.getStage_id(), explor_id);//获取踏勘点列表
    }

    /**
     * 点位列表信息接收器*
     */
    List<Exploration> pointData;

    private void addPointHandler() {
        if (pointHandler == null) pointHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (pointData == null) {
                                pointData = FastJsonUtil.JsonToGetExplorationList((String) msg.obj);
                            } else {
                                pointData.clear();
                                pointData.addAll(FastJsonUtil.JsonToGetExplorationList((String) msg.obj));
                            }
                            try {
                                List<Exploration> point = new ArrayList<>();
                                for (Exploration b : pointData) {
                                    if (b.pt_type.equals(MString.DWD)) {
                                        point.add(b);
                                    }
                                }
                                pointData.clear();
                                pointData.addAll(point);
                            } catch (Exception e) {

                            }

                            pointHandler.sendEmptyMessage(1);
                        }
                        break;
                    case 1:
                        addPoint();
                        break;
                    case 2:
                        words.setText("直线距离:");
                        SpannableString sp = new SpannableString(msg.arg1+"");
                        sp.setSpan(new ForegroundColorSpan(MyApp.activity.getResources().getColor(R.color.project_blue)),0, sp.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                        words.append(sp);

                        SpannableString sp2 = new SpannableString("米");
                        sp.setSpan(new ForegroundColorSpan(MyApp.activity.getResources().getColor(R.color.bar_right)), 0, sp2.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                        words.append(sp2);
                        bottom_title.setText((CharSequence) msg.obj);
                        break;
                    case HttpStringUtil.ERROR:
                        break;

                }
            }
        };
    }


    @Override
    protected void onDestroy() {
        myListener.close();
        baidumapstyle.onDestroy();
        super.onDestroy();
    }
}
